<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>属性管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>


    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" class="demo-ruleForm">
      <el-form-item prop="templateId">
        <el-select v-model="ruleForm.templateId" placeholder="请选择属性模板" style="width: 300px;" @change="loadAttributeList">
          <!--   :key="item.id"  是v-for的一个属性，VUE明确说明需要一个唯一的标识符     -->
          <el-option
              v-for="item in templateListOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
          </el-option>
        </el-select>
        <el-button type="primary" size="medium" style="margin-left:20px;"
                   @click="$router.push('/sys-admin/product/attribute/add-new')">添加属性
        </el-button>
      </el-form-item>
    </el-form>


    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="100" align="center"></el-table-column>
      <el-table-column prop="name" label="名称" width="200" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="description" label="简介" width="250" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <span v-text="typeText[scope.row.type]"></span>
        </template>
      </el-table-column>
      <el-table-column label="输入类型" align="center">
        <template slot-scope="scope">
          <span v-text="inputTypeText[scope.row.inputType]"></span>
        </template>
      </el-table-column>
      <el-table-column prop="valueList" label="备选值列表" width="300" header-align="center" show-overflow-tooltip></el-table-column>
      <el-table-column prop="unit" label="计量单位" width="100" align="center"></el-table-column>
      <el-table-column prop="sort" label="排序序号" width="100" align="center"></el-table-column>
      <el-table-column label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="修改属性模板" :visible.sync="dialogFormVisible">
      <el-form :model="editForm" :rules="rules" ref="ruleForm" label-width="100px">

        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="简介" prop="description">
          <el-input v-model="editForm.description" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="类型" prop="type">
          <el-input v-model="editForm.type" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="输入类型" prop="inputType">
          <el-input v-model="editForm.inputType" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="备选值列表" prop="valueList">
          <el-input v-model="editForm.valueList" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="计量单位" prop="unit">
          <el-input v-model="editForm.unit" autocomplete="off"></el-input>
        </el-form-item>

        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleUpdate()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
let localJwt = localStorage.getItem('localJwt');
export default {
  data() {
    return {
      // 显示文本常量
      typeText: ['非销售属性', '销售属性'],
      inputTypeText: ['手动录入', '单选', '多选', '单选（下拉列表）', '多选（下拉列表）'],
      templateListOptions : [],

      tableData: [],
      dialogFormVisible: false,
      editForm: {
        id: '',
        name: '',
        description: '',
        type: '',
        inputType: '',
        valueList: '',
        unit: '',
        sort: ''
      },
      ruleForm: {
        templateId: ''
      },
      rules: {
        templateId: [
          {type: 'number', required: true, message: '请选择模板', trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    openEditDialog(attribute) {
      let url = "http://localhost:8080/attribute/" + attribute.id;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.editForm = jsonResult.data;
          this.dialogFormVisible = true;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAttributeList();
            }
          });
        }
      });
    },
    handleUpdate() {
      // 要发送到后端的地址
      let url = "http://localhost:8080/attribute/" + this.editForm.id + "/update";
      let formData = this.qs.stringify(this.editForm);// 通过qs转换格式（从对象转换为formData）
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url, formData).then((response) => {// 后端那边为updateInfoById(Long id, AlbumUpdateInfoParam albumUpdateInfoParam)
                                                          // 虽然有两个参数，但是前端传过去的 formData 是一整个 id=24&name=xx&description=xx&sort=99
                                                          // Controller应该能自动匹配参数
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '修改属性成功！',
            type: 'success'
          });
          this.dialogFormVisible = false;
          this.loadAttributeList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.dialogFormVisible = false;
              this.loadAttributeList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    openDeleteConfirm(attribute) {
      this.$confirm('此操作将永久删除【' + attribute.id + '-' + attribute.name + '】属性, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(attribute);
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    handleDelete(attribute) {
      let url = "http://localhost:8080/attribute/" + attribute.id + "/delete";
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.loadAttributeList();
        } else if (jsonResult.state === 404){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadAttributeList();
            }
          });
        } else if (jsonResult.state === 501){
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    loadAttributeList() {
      let url = "http://localhost:8080/attribute/list?templateId=" + this.ruleForm.templateId;
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.tableData = jsonResult.data;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    },
    loadAttributeTemplateList() {
      let url = "http://localhost:8080/attribute-template/listAll";
      this.axios
          .create({
            'headers': {
              'Authorization': localJwt
            }
          })
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state === 200) {
          this.templateListOptions = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      });
    }
  },
  mounted() {
    this.loadAttributeTemplateList();
  }
}
</script>
